/**********************************************************
 * CategoryManagerServiceDelegator.java.java
 *
 * Created by punam
 * Last modified Date: Sep 10, 2008 1:26:34 PM by punam
 * Revision: <svn revision #>
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 **********************************************************/

package com.printeverywhere.delegator;

import static com.printeverywhere.util.AdminConstants.*;
import static com.printeverywhere.util.LoggerConstants.FIND_ALL_FAIL;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;
import com.printeverywhere.action.CategoryManagerAction;
import com.printeverywhere.action.LocationCategoriesAction;
import com.printeverywhere.dto.CategoriesCount;
import com.printeverywhere.dto.GeneralCategories;
import com.printeverywhere.dto.LocationCategories;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.HibernateUtil;
import com.printeverywhere.util.SearchCriteria;
import com.printeverywhere.util.SearchListCriteria;

/**
 * CategoryManagerServiceDelegator class list all the general categories by main
 * category user can go through the categories hierarchy. User can update the
 * Names all the generalCategories simultaneously. Any specific general category
 * is modified/deleted. deleting any parentCategory will result in all its
 * children to be deleted. CategoryManagerServiceDelegator class maintains all
 * the methods for database operation. As CRUD and retrieving list based on
 * different criteria.
 *
 * @author punam
 */
public class CategoryManagerServiceDelegator {

	/** The Constant for GET_MAX_SEQUENCE_OF_CHILD_QUERY. */
	private static final String GET_MAX_SEQUENCE_OF_CHILD_QUERY = "select max(sequence) from general_categories where categoryId != ? AND parentcategoryid=?";

	private static final String GET_MAX_SEQUENCE = "select max(sequence) from general_categories"
		.intern();

	/** The Constant GET_PARENT_QUERY. */
	private static final String GET_PARENT_QUERY = "select sequence from GeneralCategories where categoryid=";

	/** The Constant UPDATE_ALL_SEQUENCES. */
	private static final String UPDATE_ALL_SEQUENCES = "update GeneralCategories set sequence = sequence + 1 Where sequence >= ";

	/** The Constant GET_LEVEL_FOR_GIVEN_CATEOGRY. */
	private static final String GET_LEVEL_FOR_GIVEN_CATEOGRY = "select level from general_categories where categoryid= ?";

	/** The Constant DELETE_QUERY. */
	private static final String DELETE_QUERY = "delete from GeneralCategories where mainparentid=";

	/** The Constant DELETE_SUB_QUERY. */
	private static final String DELETE_SUB_QUERY = " or parentcategoryid= ";

	/** The Constant DELETE_SUB_QUERY_CATEGORY. */
	private static final String DELETE_SUB_QUERY_CATEGORY = " or categoryid=";

	/** The Constant SELECT_FOR_DELETE. */
	private static final String SELECT_FOR_DELETE = " FROM GeneralCategories where mainparentid= ";

	/** The Constant BREAD_CRUMB_QUERY1. */
	private static final String BREAD_CRUMB_QUERY1 = " FROM general_categories AS t1 "
			.intern();

	/** The Constant BREAD_CRUMB_QUERY2. */
	private static final String BREAD_CRUMB_QUERY2 = " LEFT JOIN general_categories AS t"
			.intern();

	/** The Constant BREAD_CRUMB_QUERY3. */
	private static final String BREAD_CRUMB_QUERY3 = " WHERE t1.categoryname = '"
			.intern();

	public static final String UPDATE_ICON_VALUES = "update GeneralCatagories set icon = ? where parentCategoryId = ?";

	public static final String UPDATE_ALL_ICON_VALUES = "update GeneralCatagories set icon = ? where mainParentId = ?";
	/** The logger. */

	public static final String UPDATE_TEMPLATE_VALUES = "update GeneralCatagories set template = ? where parentCategoryId = ?";

	public static final String UPDATE_ALL_TEMPLATE_VALUES = "update GeneralCatagories set template = ? where mainParentId = ?";

	private static Logger logger = Logger
			.getLogger(CategoryManagerServiceDelegator.class);

	/**
	 * Gets the list of all the records from GeneralCategories table without
	 * checking any predefined criteria, It simply list all the rows from
	 * database table.
	 *
	 * @return the list
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static List<GeneralCategories> getList() throws HibernateException {
		logger.info(GET_LIST_WITHOUT_SEARCH_CRITERIA);
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			List<GeneralCategories> list = session.createCriteria(
					GeneralCategories.class).list();
			transaction.commit();
			return list;
		} catch (HibernateException e) {
			logger.error(ERROR_GET_LIST_WITHOUT_SEARCH_CRITERIA
					+ e.getMessage());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
	}

	/**
	 * Append the generalCategories object as new row in GeneralCategories
	 * table.
	 *
	 * @param GeneralCategories
	 *            the General categories
	 *
	 * @return the string
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static String add(GeneralCategories GeneralCategories)
			throws HibernateException {
		logger.info(CALLED_ADD_METHOD);
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			session.save(GeneralCategories);
			transaction.commit();
			logger.info(RECORD_ADDED);
			return RECORD_ADDED;
		} catch (HibernateException e) {
			logger.error(ERROR_IN_ADDING_THE_RECORD);
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
	}

	/**
	 * Gets the max sequence value object for GeneralCategories from database.
	 *
	 * @return the max id
	 */
	public static int getMaxSequence() {
		logger.info("Get maximum of sequece."
				.intern());
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		int sequence = 0;
		try {
			Query query = session
					.createSQLQuery(GET_MAX_SEQUENCE);
			Object[] objects = query.list().toArray();
			if (objects.length > 0) {
				if (objects[0] != null) {
					sequence = ((Integer) objects[0]);
				}
			} else {
				sequence = 0;
			}
			transaction.commit();
		} catch (HibernateException e) {
			logger
					.error("Error in Get maximum of sequece."
							.intern());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return sequence;
	}

	/**
	 * Update the given modified GeneralCategories object to the old object. The
	 * object is updated based on the primary key.
	 *
	 * @param generalCategories
	 *            the General categories
	 *
	 * @return the string
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static String update(GeneralCategories generalCategories)
			throws HibernateException {
		logger.info(CALLED_UPDATE_METHOD);
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			session.update(generalCategories);
			transaction.commit();
			logger.info(RECORD_UPDATED);
			return RECORD_UPDATED;
		} catch (HibernateException e) {
			logger.error(ERROR_IN_UPDATING_THE_RECORD);
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
	}

	/**
	 * Get maximum of sequence for the children of given parentId. If the
	 * GeneralCategory doesn't have any child the method will return 0.
	 *
	 * @param parentCategoryId
	 *            the category id
	 *
	 * @return the max of child sequence
	 */
	public static int getMaxOfChildSequence(int parentCategoryId, int categoryId) {
		logger.info("Get maximum of sequece for the children of given parentId"
				.intern());
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		int sequence = 0;
		try {
			Query query = session
					.createSQLQuery(GET_MAX_SEQUENCE_OF_CHILD_QUERY);
			query.setInteger(0, categoryId);
			query.setInteger(1, parentCategoryId);
			Object[] objects = query.list().toArray();
			if (objects.length > 0) {
				if (objects[0] != null) {
					sequence = ((Integer) objects[0]);
				}
			} else {
				sequence = 0;
			}
			transaction.commit();
		} catch (HibernateException e) {
			logger
					.error("Error in Get maximum of sequece for the children of givem parentId"
							.intern());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return sequence;
	}

	/**
	 * Gets the parent sequence value from the generalCategories table where the
	 * categoryId matches for the given categoryId.
	 *
	 * @param categoryId
	 *            the category id
	 *
	 * @return the parent sequence
	 */
	public static int getParentSequence(int categoryId) {
		logger.info("Called getParentSequence method.".intern());
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		int sequence = 0;
		try {
			Query query = session.createQuery(GET_PARENT_QUERY + categoryId);
			Object[] objects = query.list().toArray();
			if (objects[0] != null) {
				sequence = (Integer) objects[0];
			}
			transaction.commit();
		} catch (HibernateException e) {
			logger
					.error("Error in getting the parent sequence of given categoryId "
							.intern()
							+ e.getMessage());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return sequence;
	}

	/**
	 * Update the sequence values by increasing all the sequence values by 1,
	 * starting from given sequence value. It will modify all the sequence
	 * values. For updating value of currently updated GeneralCategories object.
	 *
	 * @param sequence
	 *            the sequence
	 *
	 * @return the string
	 */
	public static String updateSequences(int sequence) {
		logger.info("Called updateSequences method".intern());
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			Query query = session.createQuery(UPDATE_ALL_SEQUENCES + sequence);
			query.executeUpdate();
			transaction.commit();
		} catch (HibernateException e) {
			logger.error("Error in updating the sequence values ".intern()
					+ e.getMessage());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return ALL_THE_SEQUENCES_UPDATED;
	}

	/**
	 * Gets the level value from GeneralCategories table where the categoryId
	 * matches given categoryId.
	 *
	 * @param categoryId
	 *            the category id
	 *
	 * @return the level for given category id
	 */
	public static int getLevelForGivenCategoryId(int categoryId) {
		logger.info("Called method getLevelForGivenCategoryId.".intern());
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		int level = 0;
		try {
			Query query = session.createSQLQuery(GET_LEVEL_FOR_GIVEN_CATEOGRY);
			query.setInteger(0, categoryId);
			Object[] objects = query.list().toArray();
			if (objects.length > 0) {
				if (objects[0] != null) {
					level = (Integer) objects[0];
				}
			} else {
				level = 0;
			}

			transaction.commit();
		} catch (HibernateException e) {
			logger.error("Error in getting the level for given CategoryId "
					.intern()
					+ e.getMessage());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return level;
	}

	/**
	 * Sets Icon value as per the value passed in iconSelectedOptions.
	 *
	 * @param categoryId
	 * @param iconSelectedOptions
	 * @param icon
	 * @return
	 */
	public static String updateIconValue(int categoryId,
			int iconSelectedOptions, String icon) {
		logger.info("Called method updateIconValue.".intern());

		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		Query query = null;
		try {
			if (iconSelectedOptions == 1) {
				// Updates the icon where parentCategoryId matches the
				// categoryId
				query = session.createQuery(UPDATE_ICON_VALUES);
			} else if (iconSelectedOptions == 2) {
				// Updates all the icon where mainParentId matches the
				// categoryId
				query = null;
				query = session.createQuery(UPDATE_ALL_ICON_VALUES);
			} else {
				// updates only this categoryId icon value
				return AdminConstants.BLANK;
			}
			query.setString(0, icon);
			query.setInteger(1, categoryId);
			query.executeUpdate();
			transaction.commit();
			return RECORD_UPDATED;
		} catch (HibernateException e) {
			if (transaction != null)
				transaction.rollback();
			return AdminConstants.RECORD_NOT_UPDATED;
		} finally {
			session.close();
		}

	}

	/**
	 * Sets template value as per the value passed in iconSelectedOptions.
	 *
	 * @param categoryId
	 * @param templateSelectedOptions
	 * @param icon
	 * @return
	 */
	public static String updateTemplateValue(int categoryId,
			int templateSelectedOptions, String icon) {
		logger.info("Called method updateIconValue.".intern());

		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		Query query = null;
		try {
			if (templateSelectedOptions == 1) {
				// Updates the icon where parentCategoryId matches the
				// categoryId
				query = session.createQuery(UPDATE_TEMPLATE_VALUES);
			} else if (templateSelectedOptions == 2) {
				// Updates all the icon where mainParentId matches the
				// categoryId
				query = null;
				query = session.createQuery(UPDATE_ALL_TEMPLATE_VALUES);
			} else {
				// updates only this categoryId icon value
				return AdminConstants.BLANK;
			}
			query.setString(0, icon);
			query.setInteger(1, categoryId);
			query.executeUpdate();
			transaction.commit();
			return RECORD_UPDATED;
		} catch (HibernateException e) {
			if (transaction != null)
				transaction.rollback();
			return AdminConstants.RECORD_NOT_UPDATED;
		} finally {
			session.close();
		}

	}

	/**
	 * Deletes all the GeneralCategories where the categoryId, parentCategoryId
	 * or mainParentId matches with given id.
	 *
	 * @param id
	 *            the id
	 *
	 * @return the string
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static String delete(int id) throws HibernateException {
		logger.info(CALLED_DELETE_METHOD);
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			Query query = session.createQuery(DELETE_QUERY + id
					+ DELETE_SUB_QUERY + id + DELETE_SUB_QUERY_CATEGORY + id);
			query.executeUpdate();
			transaction.commit();
			logger.info(RECORD_DELETED);
			return RECORD_DELETED;
		} catch (HibernateException e) {
			logger.error(ERROR_IN_DELETING_THE_RECORD);
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
	}

	/**
	 * Gets the GeneralCategories object where categoryId value matches with
	 * given id.
	 *
	 * @param categoryId
	 *            the category id
	 *
	 * @return the General categories
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static GeneralCategories get(int categoryId)
			throws HibernateException {
		logger.info("Called get method".intern());
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		GeneralCategories generalCategories = new GeneralCategories();
		try {
			Criteria criteria = session.createCriteria(GeneralCategories.class)
					.add(Expression.eq(AdminConstants.CATEGORYID, categoryId));
			List<GeneralCategories> list = criteria.list();
			generalCategories = (list.size() > 0) ? list.get(0)
					: new GeneralCategories();
			transaction.commit();
		} catch (HibernateException e) {
			logger.info("Error in getting the object for given categoryId "
					.intern()
					+ e.getMessage());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return generalCategories;
	}

	/**
	 * The main method.
	 *
	 * @param args
	 *            the arguments
	 */


	/**
	 * Gets the GeneralCategories list where id parameter matches for
	 * categoryId, parentCategoryId or mainParentId if any of the value matches
	 * the object is returned in the list for confirming deletion.
	 *
	 * @param id
	 *            the id
	 *
	 * @return the categories to delete
	 */
	public static List<GeneralCategories> getCategoriesToDelete(int id) {
		logger.info("Called getCategoriesToDelete method.");
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		List<GeneralCategories> generalCategoriesList = new ArrayList<GeneralCategories>();
		try {
			Query query = session.createQuery(SELECT_FOR_DELETE + id
					+ DELETE_SUB_QUERY + id + DELETE_SUB_QUERY_CATEGORY + id);
			generalCategoriesList = query.list();
			transaction.commit();
		} catch (HibernateException e) {
			logger.error("Error in getting categories got given id "
					+ e.getMessage());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return generalCategoriesList;
	}

	/**
	 * Gets the list of the GeneralCategories objects based on the keys and
	 * values specified. It returns the list iff the condition in given criteria
	 * satisfies. For Ex: if it requires list for only those record with given
	 * parentCategoryId, it looks for the given searching criteria and retrieves
	 * list accordingly.
	 *
	 * @param searchCriteria
	 *            the search criteria
	 *
	 * @return the list
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static List<GeneralCategories> getList(SearchCriteria searchCriteria)
			throws HibernateException {
		logger.info(GET_LIST_WITH_SEARCH_CRITERIA);
		Session session = HibernateUtil.getSession();
		Criteria criteria = session.createCriteria(GeneralCategories.class);
		String orderBY = searchCriteria.getOrderBy();
		if (orderBY != null) {
			if (searchCriteria.isAsc()) {
				criteria.addOrder(Order.asc(orderBY));
			} else {
				criteria.addOrder(Order.desc(orderBY));
			}
		}
		Set<String> keys = searchCriteria.getAttributeNames();
		Iterator<String> it = keys.iterator();
		String key = null;
		Object value = null;
		while (it.hasNext()) {
			key = it.next();
			value = searchCriteria.getAttribute(key);
			criteria.add(Restrictions.eq(key, value));
		}
		Transaction transaction = session.beginTransaction();
		List<GeneralCategories> list = new ArrayList<GeneralCategories>();

		try {
			list = criteria.list();
			transaction.commit();
		} catch (HibernateException e) {
			for (String keyexception : keys) {
				logger.error(keys);
			}
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.flush();
			HibernateUtil.closeSession();
		}
		return list;
	}

	/**
	 * Returns the list of the GeneralCategories based on the conditions
	 * specified in searchListCriteria. It checks for the given values equality,
	 * non-equality, greater, less, like, ...etc. operations.
	 *
	 * @param searchCriteria
	 *            the search criteria
	 *
	 * @return the list
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static List<GeneralCategories> getList(
			SearchListCriteria searchCriteria) throws HibernateException {
		logger.info(GET_LIST_WITH_SEARCH_LIST_CRITERIA);
		Session session = HibernateUtil.getSession();
		Criteria criteria = session.createCriteria(GeneralCategories.class);
		String orderBY = searchCriteria.getOrderBy();
		if (orderBY != null) {
			if (searchCriteria.isAsc()) {
				criteria.addOrder(Order.asc(orderBY));
			} else {
				criteria.addOrder(Order.desc(orderBY));
			}
		}
		Set<String> keys = searchCriteria.getAttributeNames();
		Iterator<String> it = keys.iterator();
		String key = null;
		Object[] value = null;
		while (it.hasNext()) {
			key = it.next();
			value = searchCriteria.getAttribute(key);
			if (((String) value[1]).equals(SearchListCriteria.EQ)) {
				criteria.add(Restrictions.eq(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.GE)) {
				criteria.add(Restrictions.ge(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.GT)) {
				criteria.add(Restrictions.gt(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.ILIKE)) {
				criteria.add(Restrictions.ilike(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.ISNOTNULL)) {
				criteria.add(Restrictions.isNotNull(key));
			} else if (((String) value[1]).equals(SearchListCriteria.ISNULL)) {
				criteria.add(Restrictions.isNull(key));
			} else if (((String) value[1]).equals(SearchListCriteria.LE)) {
				criteria.add(Restrictions.le(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.LIKE)) {
				criteria.add(Restrictions.like(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.LT)) {
				criteria.add(Restrictions.lt(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.NE)) {
				criteria.add(Restrictions.ne(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.IN)) {
				criteria.add(Restrictions.in(key, (Object[]) value[0]));
			}
		}
		Transaction transaction = session.beginTransaction();
		List<GeneralCategories> list = new ArrayList<GeneralCategories>();
		try {
			list = criteria.list();
			transaction.commit();
		} catch (HibernateException e) {
			for (String keyexception : keys) {
				logger.info(keys);
			}
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.flush();
			HibernateUtil.closeSession();
		}
		return list;
	}


	/**
	 * Returns the list of the GeneralCategories based on the conditions
	 * specified in searchListCriteria. It checks for the given values equality,
	 * non-equality, greater, less, like, ...etc. operations.<br>
	 * By default sort by categoryName in ascending order.
	 *
	 * @param searchCriteria
	 *            the search criteria
	 *
	 * @return the list
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static List<GeneralCategories> getSortedList(
			SearchListCriteria searchCriteria) throws HibernateException {
		logger.info(GET_LIST_WITH_SEARCH_LIST_CRITERIA);
		Session session = HibernateUtil.getSession();
		Criteria criteria = session.createCriteria(GeneralCategories.class);
		String orderBY = searchCriteria.getOrderBy();
		if (orderBY != null) {
			if (searchCriteria.isAsc()) {
				criteria.addOrder(Order.asc(orderBY));
			} else {
				criteria.addOrder(Order.desc(orderBY));
			}
		}
		Set<String> keys = searchCriteria.getAttributeNames();
		Iterator<String> it = keys.iterator();
		String key = null;
		Object[] value = null;
		while (it.hasNext()) {
			key = it.next();
			value = searchCriteria.getAttribute(key);
			if (((String) value[1]).equals(SearchListCriteria.EQ)) {
				criteria.add(Restrictions.eq(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.GE)) {
				criteria.add(Restrictions.ge(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.GT)) {
				criteria.add(Restrictions.gt(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.ILIKE)) {
				criteria.add(Restrictions.ilike(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.ISNOTNULL)) {
				criteria.add(Restrictions.isNotNull(key));
			} else if (((String) value[1]).equals(SearchListCriteria.ISNULL)) {
				criteria.add(Restrictions.isNull(key));
			} else if (((String) value[1]).equals(SearchListCriteria.LE)) {
				criteria.add(Restrictions.le(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.LIKE)) {
				criteria.add(Restrictions.like(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.LT)) {
				criteria.add(Restrictions.lt(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.NE)) {
				criteria.add(Restrictions.ne(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.IN)) {
				criteria.add(Restrictions.in(key, (Object[]) value[0]));
			}
		}
		Transaction transaction = session.beginTransaction();
		List<GeneralCategories> list = new ArrayList<GeneralCategories>();
		try {
			list = criteria.list();
			transaction.commit();
		} catch (HibernateException e) {
			for (String keyexception : keys) {
				logger.info(keys);
			}
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.flush();
			HibernateUtil.closeSession();
		}
		return list;
	}


	/**
	 * Find all.
	 *
	 * @return the user accounts count
	 */
	@SuppressWarnings("unchecked")
	public static CategoriesCount findAll() {
		if(logger.isDebugEnabled())
			logger.debug("categories count".intern());
		try {
			List<CategoriesCount> list = HibernateUtil.getSession().createCriteria(CategoriesCount.class).list();
			if(list.size()>0){
				return list.get(0);
			}
			else
			return null;
		} catch (RuntimeException re) {
			logger.error(FIND_ALL_FAIL, re);
			throw re;
		}
	}
	/**
	 * Returns the list of breadCruembs to display in the "Top" link of General
	 * categories.
	 *
	 * @param generalCategories
	 *            the general categories
	 *
	 * @return the bread crumb list
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static List<Integer> getBreadCrumbList(
			GeneralCategories generalCategories, GeneralCategories mainParentGeneralCategories) throws HibernateException {
		logger.info("In getBreadCrumbList method.".intern());
		List<Integer> breadCrumbList = new ArrayList<Integer>();
		List<GeneralCategories> generalCategoriesList = new ArrayList<GeneralCategories>();

		StringBuffer selectQueryBuffer = new StringBuffer();
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		Object[] object;
		try {
			selectQueryBuffer.append(SELECT);
			for (int index = 0; index < generalCategories.getLevel(); index++) {
				selectQueryBuffer.append(T);
				selectQueryBuffer.append(index + 1);
				selectQueryBuffer.append(DOT);
				selectQueryBuffer.append(CATEGORYID);
				selectQueryBuffer.append(BLANK);
				selectQueryBuffer.append(AS);
				selectQueryBuffer.append(LEV.intern());
				selectQueryBuffer.append(index + 1);
				if (index < generalCategories.getLevel() - 1)
					selectQueryBuffer.append(COMMA);
			}
			selectQueryBuffer.append(BREAD_CRUMB_QUERY1);
			int indexJoin;
			for (indexJoin = 0; indexJoin < generalCategories.getLevel(); indexJoin++) {
				selectQueryBuffer.append(BREAD_CRUMB_QUERY2);
				selectQueryBuffer.append(indexJoin + 2);
				selectQueryBuffer.append(ON);
				selectQueryBuffer.append(T);
				selectQueryBuffer.append(indexJoin + 2);
				selectQueryBuffer.append(DOT);
				selectQueryBuffer.append(PARENTCATEGORYID);
				selectQueryBuffer.append(BLANK);
				selectQueryBuffer.append(EQUALS);
				selectQueryBuffer.append(T);
				selectQueryBuffer.append(indexJoin + 1);
				selectQueryBuffer.append(DOT);
				selectQueryBuffer.append(CATEGORYID);
				if (generalCategories.getLevel() == 2)
					indexJoin++;
			}
			String categoryName = generalCategories.getCategoryName().replaceAll("'".intern(), "\\\\'".intern());
			selectQueryBuffer.append(BREAD_CRUMB_QUERY3);
			selectQueryBuffer.append(mainParentGeneralCategories
					.getCategoryName());
			selectQueryBuffer.append(QUOTE_AND);
			selectQueryBuffer.append(T);
			selectQueryBuffer.append(indexJoin);
			selectQueryBuffer.append(DOT);
			selectQueryBuffer.append(CATEGORYNAME_EQULAS);
			selectQueryBuffer.append(categoryName);
			selectQueryBuffer.append(QUOTE_SEMICOLON);
			Query query = session.createSQLQuery(selectQueryBuffer.toString());
			try {
				object = (Object[]) query.list().get(0);
			} catch (Exception e) {
				object = new Object[] { query.list().get(0) };
			}
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			logger.error("Error in getting list for breadcrumb.".intern());
			throw e;
		}
		for (int index = 0; index < object.length; index++) {
			breadCrumbList.add(Integer.valueOf(object[index]
					.toString()));
			/*generalCategoriesList.add(get(Integer.parseInt(object[index]
					.toString())));*/
		}
		return breadCrumbList;
	}

	/**
	 * Returns tree Structure to display for delete confirmation.
	 *
	 * @param categories
	 *            the categories
	 * @param index
	 *            the index
	 * @param list
	 *            the list
	 *
	 * @return the list< string>
	 */
	public static List<String> show(GeneralCategories categories, String index,
			List<String> list) {
		if (categories.getGeneralCategorieses().size() > 0) {
			for (Iterator iterator = categories.getGeneralCategorieses()
					.iterator(); iterator.hasNext();) {
				GeneralCategories type = (GeneralCategories) iterator.next();
				if (type.getCategoryId() == type.getGeneralCategories()
						.getCategoryId()) {
					if (iterator.hasNext()) {
						type = (GeneralCategories) iterator.next();
					} else {
						break;
					}
				}
				String display = index + type.getCategoryName()
						+ AdminConstants.OPEN_PARENTHESE
						+ (type.getGeneralCategorieses().size())
						+ AdminConstants.CLOSE_PARENTHESE;
				list.add(display);
				show(type, "---"+ index, list);
				logger.info(" display -- " + display);
			}
		}
		return list;
	}


	public static List<GeneralCategories> getParentList(){
		List<GeneralCategories> tempGeneralCategoriesList=(List<GeneralCategories>) ActionContext.getContext().getApplication().get(AdminConstants.GENERALCATEGORIES);
		List<GeneralCategories> tempList=new ArrayList<GeneralCategories>();
		for (Iterator iterator = tempGeneralCategoriesList.iterator(); iterator.hasNext();) {
		GeneralCategories tempGeneralCategories = (GeneralCategories) iterator.next();
			if (tempGeneralCategories.getLevel() == AdminConstants.ONE_NUMBER){
				tempList.add(tempGeneralCategories);
			}
		}
		return tempList;
	}

	public static List<GeneralCategories> removeParentfromSet(List<GeneralCategories> list , List<GeneralCategories> newlist ){
		List<GeneralCategories> parentList = getParentList();
		for (Iterator iterator = parentList.iterator(); iterator.hasNext();) {
			GeneralCategories generalCategories = (GeneralCategories) iterator.next();

		}
		return parentList;
	}



	public static GeneralCategories removeParentfromSet(GeneralCategories categories ) {
		if(categories.getGeneralCategorieses().size()>0){
			Set<GeneralCategories> set =new HashSet<GeneralCategories>(categories.getGeneralCategorieses());
			for (GeneralCategories category : categories.getGeneralCategorieses()) {
				if(category.getCategoryId()== categories.getCategoryId()){
					set.remove(category);
				}else if(categories.getGeneralCategorieses().size()>0){
					removeParentfromSet(category);
				}
				categories.setGeneralCategorieses(set);
			}
		}
		return categories;
	}

	public static void main(String[] args) {
		removeParentfromSet(get(6));
	}

}
